package com.bangmai.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

/**
 * �ļ�����������
 * @author dellpc
 *
 */
public class FileUtil {
	/**
	 * ��ȡ�ļ�����
	 * @param filePath �ļ�·��
	 * @return �����ļ�����
	 * @throws IOException 
	 */
	public static String readFile(String filePath) throws IOException{
		File file=new File(filePath);
        if(!file.exists()||file.isDirectory())
            throw new FileNotFoundException();
        BufferedReader br=new BufferedReader(new FileReader(file));
        String temp=null;
        StringBuffer sb=new StringBuffer();
        temp=br.readLine();
        while(temp!=null){
            sb.append(temp);
            temp=br.readLine();
        }
        return sb.toString();
		 
	}
	
	
	
	
	/**
	 * ȡ���ļ���������
	 * @param startTag
	 * @param endTag
	 * @param filePath
	 * @return
	 * @throws IOException
	 */
	public static String readFileContent(String startTag,String endTag,String filePath) throws IOException{
		
		File file=new File(filePath);
        if(!file.exists()||file.isDirectory())
            throw new FileNotFoundException();
        BufferedReader br=new BufferedReader(new FileReader(file));
        String temp=null;
        StringBuffer sb=new StringBuffer();
        temp=br.readLine();
        Boolean start=false;
        while(temp!=null){
        	if (temp.equals(startTag)) {
        		start=true;
        		
			}
        	
          if(!temp.equals(startTag)&&start==true)  sb.append(temp);
           
          temp=br.readLine().trim();
            
            
            if (temp!=null&&temp.equals(endTag)) {
            	start=false;
				break;
			}
        }
        return sb.toString();
		 
		
		
	}
	
	/**
	 * �����ļ�
	 * @param filePath ·��+�ļ���
	 * @param fileContent ����
	 * @throws UnsupportedEncodingException
	 * @throws IOException
	 */
	public static void saveFile(String filePath,String fileContent) throws UnsupportedEncodingException, IOException{
		
		File file=new File(filePath);
        if(!file.exists())
            file.createNewFile();
        FileOutputStream out=new FileOutputStream(file,true);        
         
        StringBuffer sb=new StringBuffer();
        sb.append(fileContent);
        out.write(sb.toString().getBytes("utf-8"));
         
        out.close();
        sb=null;
        file=null;
		
	}
	
	   /**
	    * ȡ���ַ�����������
	 * @param startTag
	 * @param endTag
	 * @param str
	 * @return
	 * @throws IOException
	 */
	public static String readStringContent(String startTag,String endTag,String str) throws IOException{
			
			int startIndex=str.indexOf(startTag)+startTag.length();
			int endIndex=str.indexOf(endTag);
			return str.substring(startIndex, endIndex);
		}
	
	/**
	 * ȡ�õ�ǰʱ�� ��ʽΪ(yyyyMMddHHmmss)
	 * @return
	 */
	public static String getTimeString1(){
		
		Date nowTime=new Date(); 
		System.out.println(nowTime); 
		SimpleDateFormat time=new SimpleDateFormat("yyyyMMddHHmmss"); 
		return time.format(nowTime);
	}
	/**
	 * ȡ�õ�ǰʱ�� ��ʽΪ(yyyyMMddHHmmssms)
	 * @return
	 */
	public static String getTimeString2(){
		
		Date nowTime=new Date(); 
		System.out.println(nowTime); 
		SimpleDateFormat time=new SimpleDateFormat("yyyyMMddHHmmssms"); 
		return time.format(nowTime);
	}
	
	
	 public static Date string2Date(String dateStr) throws ParseException{
		 
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		 Date date = sdf.parse(dateStr);
		 return date;
		 
	 }	
	 
     public static Date string2Date2(String dateStr) throws ParseException{
		 
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		 Date date = sdf.parse(dateStr);
		 return date;
		 
	 }	
	
	public static String Date2String(Date date){
		
		SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		return time.format(date);
		
	}
	
	public static File[] getFiles(String path){
		
		 File file=new File(path);
		  File[] tempList = file.listFiles();
		  return tempList;
	}
	
	public static ArrayList<String[]> getXmlNode(String FilePath) throws DocumentException{
		
		 ArrayList<String[]> values=new ArrayList<String[]>();
		
		SAXReader reader=new SAXReader();
		
		Document document=reader.read(new File(FilePath));
		
		Element root=document.getRootElement();
		
		 for ( Iterator i = root.elementIterator(); i.hasNext(); ) {
		       Element element = (Element) i.next();
		       // do something
		       for (int k = 0, size = element.nodeCount(); k < size; k++)  {
		    	   Node node = element.node(k);
		    	  if (node.getName()!=null) {
		    		  String[] nodeData={node.getName(),node.getStringValue()};
		    		  values.add(nodeData);
				 }
		     }
		 }
		 return values;
	}
	public static String getExtensionName(String filename) {   
        if ((filename != null) && (filename.length() > 0)) {   
            int dot = filename.lastIndexOf('.');   
            if ((dot >-1) && (dot < (filename.length() - 1))) {   
                return filename.substring(dot + 1);   
            }   
        }   
        return filename;   
    }   
	
	 /** 
     * ɾ���ļ����У� 
     * 
     * @param file �ļ����У� 
     */ 
    public static void delete(File file) { 
            if (!file.exists()) return; 
            if (file.isFile()) { 
//                    file.delete(); 
                    file.deleteOnExit();
            } else { 
                    for (File f : file.listFiles()) { 
                            delete(f); 
                    } 
                    file.delete(); 
            } 
    } 
    /** 
     * �����ļ����У���һ��Ŀ���ļ��� 
     * 
     * @param resFile             Դ�ļ����У� 
     * @param objFolderFile Ŀ���ļ��� 
     * @throws IOException �쳣ʱ�׳� 
     */ 
    public static void copy(File resFile, File objFolderFile) throws IOException { 
            if (!resFile.exists()) return; 
            if (!resFile.exists()) {
				resFile.createNewFile();
			}
            if (resFile.isFile()) { 
                    //�����ļ���Ŀ��� 
                    InputStream ins = new FileInputStream(resFile); 
                    FileOutputStream outs = new FileOutputStream(objFolderFile); 
                    byte[] buffer = new byte[1024 * 512]; 
                    int length; 
                    while ((length = ins.read(buffer)) != -1) { 
                            outs.write(buffer, 0, length); 
                    } 
                    ins.close(); 
                    outs.flush(); 
                    outs.close(); 
            } else { 
                    String objFolder = objFolderFile.getPath() + File.separator + resFile.getName(); 
                    File _objFolderFile = new File(objFolder); 
                    _objFolderFile.mkdirs(); 
                    for (File sf : resFile.listFiles()) { copy(sf, new File(objFolder)); 
                    } 
            } 
    } 
    /**
     * �����λ�����
     * @return
     */
    public  static  String get4RandomString(){
    	String randomString=String.valueOf((int)(Math.random()*9000)+1000);;
    	
    	return randomString;
    }
    /**
     * �����λ�����
     * @return
     */
    public  static  String get3RandomString(){
    	String randomString=String.valueOf((int)(Math.random()*900)+100);;
    	
    	return randomString;
    }
    
    /** 
     * 移除所有文件 
     *  
     * @param strPath 
     */  
    public static void removeAllFile(String strPath) {  
        File file = new File(strPath);  
        if (!file.exists()) {  
            return;  
        }  
        if (!file.isDirectory()) {  
            return;  
        }  
        String[] fileList = file.list();  
        File tempFile = null;  
        for (int i = 0; i < fileList.length; i++) {  
            if (strPath.endsWith(File.separator)) {  
                tempFile = new File(strPath + fileList[i]);  
            } else {  
                tempFile = new File(strPath + File.separator + fileList[i]);  
            }  
            if (tempFile.isFile()) {  
                tempFile.delete();  
            }  
            if (tempFile.isDirectory()) {  
                removeAllFile(strPath + "/" + fileList[i]);// 删除文件夹里面的文件  
//                removeFolder(strPath + "/" + fileList[i]);// 删除文件夹  
            }  
        }  
    }  
    

}
